﻿using System;
using System.Configuration;
using System.Drawing;
using System.Web;
using Altairis.Nemesis.Gallery.Configuration;

namespace Altairis.Nemesis.Gallery {
    public class ThumbnailHandler : IHttpHandler {

        GallerySection config;

        public ThumbnailHandler() {
            this.config = GallerySection.GetCurrentOrDefault();
        }

        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context) {
            // Check extension mapping
            string fileName = context.Request.PhysicalPath;
            if (!fileName.EndsWith(".jpg.tn", StringComparison.OrdinalIgnoreCase))
                throw new NotSupportedException("ThumbnailHandler can be mapped only to *.jpg.tn extension");

            // Ger real file name
            fileName = fileName.Substring(0, fileName.Length - 3);

            // Check if file exists
            if (!System.IO.File.Exists(fileName)) throw new HttpException(404, "Object Not Found");

            // Find appropriate size information
            string sizeName = context.Request.QueryString["Q"] ?? this.config.Sizes.Default;
            SizeElement selectedSizeInfo = null;
            foreach (SizeElement sizeInfo in this.config.Sizes) {
                if (sizeInfo.Name.Equals(sizeName, StringComparison.OrdinalIgnoreCase)) {
                    selectedSizeInfo = sizeInfo;
                    break;
                }
            }
            selectedSizeInfo = selectedSizeInfo ?? new SizeElement { Width = 150, Height = 150, BackgroundColor = Color.White };

            // Compute size of thumbnail
            Size thumbnailSize = new Size(selectedSizeInfo.Width, selectedSizeInfo.Height);

            // Create thumbnail
            if (selectedSizeInfo.BackgroundColor == Color.Transparent) {
                using (Image sourceImage = Image.FromFile(fileName))
                using (Image targetImage = Utils.ResizeImage(sourceImage, thumbnailSize)) {
                    targetImage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            else {
                using (Image sourceImage = Image.FromFile(fileName))
                using (Image targetImage = Utils.ResizeImage(sourceImage, thumbnailSize, selectedSizeInfo.BackgroundColor)) {
                    targetImage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            context.Response.ContentType = "image/jpeg";

            // Setup caching 
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            context.Response.Cache.SetExpires(DateTime.Now.AddHours(1));
            context.Response.AddFileDependency(fileName);
            context.Response.Cache.SetLastModifiedFromFileDependencies();
            context.Response.Cache.SetETagFromFileDependencies();
            context.Response.Cache.VaryByParams["Q"] = true;
        }

    }
}